<template>
  <div class="cart-container">
    <el-card>
      <template #header>
        <div class="cart-header">
          <h2>购物车</h2>
        </div>
      </template>

      <div v-if="loading" class="loading">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="items.length === 0" class="empty">
        <el-empty description="购物车是空的">
          <el-button type="primary" @click="$router.push('/')">去购物</el-button>
        </el-empty>
      </div>

      <template v-else>
        <div class="cart-items">
          <el-table :data="items" style="width: 100%">
            <el-table-column label="商品" min-width="400">
              <template #default="{ row }">
                <div class="product-info">
                  <el-image :src="row.imageUrl" :preview-src-list="[row.imageUrl]" fit="cover" />
                  <div class="product-detail">
                    <h3>{{ row.name }}</h3>
                    <p class="price">¥{{ row.price }}</p>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="数量" width="200">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.quantity"
                  :min="1"
                  :max="row.stock"
                  @change="(value) => handleQuantityChange(row.id, value)"
                />
              </template>
            </el-table-column>

            <el-table-column label="小计" width="150">
              <template #default="{ row }">
                <span class="subtotal">¥{{ (row.price * row.quantity).toFixed(2) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button type="danger" size="small" @click="handleRemove(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="cart-footer">
          <div class="total">
            总计: <span class="amount">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div class="actions">
            <el-button @click="$router.push('/')">继续购物</el-button>
            <el-button type="primary" @click="handleCheckout">结算</el-button>
          </div>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useStore()
const router = useRouter()

const loading = ref(false)
const items = computed(() => store.state.cart.items)
const totalAmount = computed(() => {
  return items.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

const loadCartItems = async () => {
  loading.value = true
  try {
    await store.dispatch('cart/getCartItems')
  } catch (error) {
    ElMessage.error('加载购物车失败')
  } finally {
    loading.value = false
  }
}

const handleQuantityChange = async (itemId: number, quantity: number) => {
  try {
    await store.dispatch('cart/updateQuantity', { itemId, quantity })
  } catch (error) {
    ElMessage.error('更新数量失败')
  }
}

const handleRemove = async (itemId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    await store.dispatch('cart/removeFromCart', itemId)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleCheckout = () => {
  if (items.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }
  router.push('/checkout')
}

onMounted(() => {
  loadCartItems()
})
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h2 {
  margin: 0;
}

.loading, .empty {
  padding: 40px 0;
  text-align: center;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.product-info .el-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.product-detail h3 {
  margin: 0 0 10px;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  margin: 0;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.cart-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.total {
  margin-right: 20px;
  font-size: 16px;
}

.amount {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.actions {
  display: flex;
  gap: 10px;
}
</style> 